package spring.aop;

import org.apache.commons.lang3.StringUtils;
import spring.exceptions.AopParseException;

import java.util.HashSet;
import java.util.Set;

public class AdviceMethod {

    private final Set<Class<?>> rollbackForSet = new HashSet<>(8);
    private String name;
    private String propagation;
    private boolean readOnly;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRegular() {
        return "(" + name.replaceAll("\\*", ").+(") + ")";
    }

    public String getPropagation() {
        return propagation;
    }

    public void setPropagation(String propagation) {
        this.propagation = propagation;
    }

    public boolean isReadOnly() {
        return readOnly;
    }

    public void setReadOnly(String readOnly) {
        this.readOnly = Boolean.parseBoolean(readOnly);
    }

    public boolean isRollbackException(Throwable throwable) {
        return this.rollbackForSet.stream().anyMatch(ex -> ex == throwable.getClass());
    }

    public void setRollbackFor(String rollbackFor) {
        if (StringUtils.isBlank(rollbackFor)) {
            this.rollbackForSet.clear();
            this.rollbackForSet.add(RuntimeException.class);
            return;
        }
        String[] strings = rollbackFor.split(",");
        try {
            for (String string : strings) {
                String exStr = string.trim().replaceAll("\n", "").replaceAll("\r", "");
                if (StringUtils.isBlank(exStr)) {
                    continue;
                }
                Class<?> throwableClass = Class.forName(exStr);
                this.rollbackForSet.add(throwableClass);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new AopParseException("异常类型指定错误，请正确的提供异常的具体包名+类名，如不指定默认回滚RuntimeException。", e);
        }
    }
}
